<!-- 需求列表  -->
<template>
  <pageHeader
    title="产品BOM历史版本"
    :breadCrumb="['工厂建模', '产品BOM管理', '历史版本']"
    show-back
  />

  <div class="table-info">
    <div class="tab">产品信息</div>
    <a-form :model="bomDetails" ref="refForm" auto-label-width class="form">
      <a-row :gutter="15">
        <a-col :span="12">
          <a-form-item label="关联产品" field="productId">
            <ProductChoice
              :disabled="!!bomDetails.id || !!route.query.historyId"
              ref="refProductChoice"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="产品编码">
            <a-input
              placeholder="无需输入，自动带入"
              :model-value="bomDetails.management?.number"
              disabled
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="规格型号">
            <a-input
              placeholder="无需输入，自动带入"
              :model-value="bomDetails.management?.spec"
              disabled
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="基本单位">
            <a-input
              placeholder="无需输入，自动带入"
              :model-value="bomDetails.management?.unitData?.name"
              disabled
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="产品属性">
            <a-select
              placeholder="无需输入，自动带入"
              :model-value="bomDetails.management?.attribute"
              disabled
            >
              <a-option :value="1">自制</a-option>
              <a-option :value="2">委外</a-option>
              <a-option :value="3">虚拟</a-option>
              <a-option :value="4">采购</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="tab">
      <div>产品BOM版本列表</div>
    </div>
    <a-table
      ref="refTable"
      :data="tableList"
      @select="([event]) => loadBomDetails(event)"
      @row-click="({ id }) => loadBomDetails(id)"
      :pagination="false"
      row-key="id"
      :row-selection="{
        type: 'radio',
      }"
    >
      <template #columns>
        <a-table-column
          v-for="header in [
            { code: 'bomCode', name: 'BOM编码', width: 200 },
            { code: 'bomName', name: 'BOM名称', width: 200 },
            { name: '产品编码' },
            { name: '产品名称' },
            { name: '规格型号' },
            { name: '基本单位' },
            { name: '状态' },
          ]"
          :key="header.name"
          :width="header.width || 200"
          :title="header.name"
          :data-index="header.code"
          align="center"
        >
          <template #cell="{ record }" v-if="!header.code">
            <template v-if="header.name === '状态'">
              <a-typography-text
                type="success"
                v-if="record.historyState === 1"
              >
                启用
              </a-typography-text>
              <a-typography-text type="danger" v-if="record.historyState === 2">
                停用
              </a-typography-text>
            </template>
            <template v-if="header.name === '产品编码'">
              {{ record.management?.number }}
            </template>
            <template v-if="header.name === '产品名称'">
              {{ record.management?.name }}
            </template>
            <template v-if="header.name === '规格型号'">
              {{ record.management?.spec }}
            </template>
            <template v-if="header.name === '基本单位'">
              {{ record.management?.unitData?.name }}
            </template>
          </template>
        </a-table-column>
        <a-table-column
          :width="120"
          fixed="right"
          title="启用版本"
          align="center"
        >
          <template #cell="{ record }">
            <a-space>
              <a-switch
                @click="switchClick(record)"
                :model-value="record.historyState"
                :checked-value="1"
                :unchecked-value="2"
              />
            </a-space>
          </template>
        </a-table-column>
        <a-table-column :width="120" fixed="right" title="操作" align="center">
          <!-- <template #cell="{ record }">
          <a-space>
            <a-switch
              @click="switchClick(record)"
              :model-value="record.historyState"
              :checked-value="1"
              :unchecked-value="2"
            />
          </a-space>
        </template> -->
        </a-table-column>
      </template>
    </a-table>
    <div
      class="tab"
      style="margin-top: 20px; display: flex; justify-content: space-between"
    >
      <div>产品bom信息</div>
      <a-space>
        <a-button @click="isEdit = true" v-if="!isEdit" type="primary">
          修改
        </a-button>
        <a-button
          @click="
            () => {
              loadBomDetails(bomDetails.id);
            }
          "
          v-if="isEdit"
          >取消</a-button
        >
        <a-button type="primary" @click="subEdit" v-if="isEdit">
          保存
        </a-button>
      </a-space>
    </div>
    <a-form :model="bomDetails" ref="refForm" auto-label-width class="form">
      <a-row :gutter="15">
        <a-col :span="12">
          <a-form-item label="产品BOM编码">
            <a-input
              placeholder="无需输入，系统自动生成..."
              disabled
              v-model="bomDetails.bomCode"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="BOM名称" field="bomName">
            <a-input
              :disabled="!isEdit"
              v-model="bomDetails.bomName"
              placeholder="请输入产品BOM名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="BOM版本号" field="bomEdition">
            <a-input
              v-model="bomDetails.bomEdition"
              placeholder="请输入产品BOM版本号"
              :disabled="!isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="启用状态" field="state">
            <a-select
              v-model="bomDetails.state"
              placeholder="请选择"
              :disabled="!isEdit"
            >
              <a-option
                v-for="(item, index) in ['启用', '停用']"
                :key="item"
                :value="index + 1"
              >
                {{ item }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="tab">产品BOM明细</div>
    <ProductChoice @choice="productBomChoice" v-show="isEdit">
      <a-button type="primary" v-show="isEdit">
        <template #icon>
          <icon-plus />
        </template>
        添加产品BOM
      </a-button>
    </ProductChoice>
    <div class="tab"></div>
    <a-table :data="productBomDetailList">
      <!-- arco-table的插槽，默认为columns -->
      <template #columns>
        <a-table-column
          title="BOM名称"
          :width="200"
          data-index="productBomDetail.bomName"
          align="center"
        />
        <a-table-column
          title="BOM版本号"
          :width="200"
          data-index="productBomDetail.bomEdition"
          align="center"
        />
        <a-table-column
          title="物料编码"
          :width="200"
          data-index="productBomDetail.management.number"
          align="center"
        />
        <a-table-column
          title="物料名称"
          :width="200"
          data-index="productBomDetail.management.name"
          align="center"
        />
        <a-table-column
          title="规格型号"
          :width="200"
          data-index="productBomDetail.management.spec"
          align="center"
        />
        <a-table-column
          title="单位"
          :width="180"
          data-index="productBomDetail.management.unitData.name"
          align="center"
        />

        <!-- <a-table-column :width="130" title="材料属性" align="center">
          <template #cell="{ record }">
            {{
              record.attribute === 1
                ? '自制'
                : record.attribute === 2
                ? '委外'
                : record.attribute === 3
                ? '虚拟'
                : '采购'
            }}
          </template>
        </a-table-column> -->
        <a-table-column :width="130" title="材料属性" align="center">
          <template #cell="{ record }">
            <a-select
              v-model="record.productBomDetail.management.attribute"
              disabled
            >
              <a-option :value="1">自制</a-option>
              <a-option :value="2">委外</a-option>
              <a-option :value="3">虚拟</a-option>
              <a-option :value="4">采购</a-option>
            </a-select>
          </template>
        </a-table-column>

        <a-table-column
          :width="130"
          fixed="right"
          title="标准用量"
          align="center"
        >
          <template #cell="{ record }">
            <a-input-number
              v-model="record.dosage"
              placeholder="标准用量"
              hide-button
              :disabled="!isEdit"
            />
          </template>
        </a-table-column>
        <a-table-column
          :width="130"
          fixed="right"
          title="损耗率"
          align="center"
        >
          <template #cell="{ record }">
            <a-input-number
              v-model="record.wastage"
              :max="100"
              :min="1"
              hide-button
              :disabled="!isEdit"
              placeholder="损耗率"
            >
              <template #suffix> % </template>
            </a-input-number>
          </template>
        </a-table-column>
        <a-table-column :width="80" fixed="right" title="操作" align="center">
          <template #cell="{ rowIndex }">
            <a-space>
              <a-popconfirm
                content="是否删除该数据?"
                type="error"
                @ok="productBomDetailList.splice(rowIndex, 1)"
              >
                <a-link status="danger"> 删除 </a-link>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, onMounted, ref, nextTick } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { TbomBase, TProductBomDetail } from '@/api/FactoryModeling/type';
  import {
    GetProductBomPage,
    DelProductBom,
    CheckProductBom,
    GetProductBom,
    EditProductBom,
    AddProductBom,
    GetProductBomTree,
    EditProductBomHistoryState,
  } from '@/api/FactoryModeling';
  import { Message } from '@arco-design/web-vue';

  let isEdit = ref(false);
  let productBomDetailList = ref<TProductBomDetail[]>([]);

  const router = useRouter();
  const route = useRoute();

  let refTable = ref();
  let tableList = ref<any[]>([]);

  // 获取需求列表
  const getTableList = async () => {
    try {
      let res = await GetProductBomPage({
        page: 1,
        size: -1,
        id: route.query.saveId,
        bomCode: route.query.bomCode,
      });
      tableList.value = res.content || [];
      return Promise.resolve(res.content || []);
    } catch (err: unknown) {
      console.error(err);
      return Promise.resolve();
    }
  };
  let switchClick = async ({ historyState, id, bomCode }: any) => {
    if (historyState === 1) return Message.error('请通过启用其他历史版本关闭');
    await EditProductBomHistoryState({ id, bomCode });
    getTableList();
  };
  const del = async (id: number, bomCode: string) => {
    let check = await CheckProductBom({ treeId: id });
    if (!check.length) {
      await DelProductBom({ id, bomCode });
      getTableList();
    } else {
      Message.error('该BOM已被其他BOM引用，不可删除');
    }
  };

  let bomDetails = reactive<TbomBase>({});
  let refProductChoice = ref();
  let loadBomDetails = async (id: any) => {
    try {
      let res = await GetProductBom({ id });
      let data: TbomBase = {
        ...res,
        id: route.query.copyId || route.query.historyId ? undefined : res.id,
        productBomDetail:
          res.productBomDetail.map((item: any) => {
            return {
              ...item,
              wastage: Number(item.wastage),
              id:
                route.query.copyId || route.query.historyId
                  ? undefined
                  : item.id,
            };
          }) || [],
        productId: route.query.copyId ? undefined : res.productId,
        management: route.query.copyId ? undefined : res.management,
      };
      refTable.value.select(id);
      Object.assign(bomDetails, data);
      productBomDetailList.value = data.productBomDetail || [];
      refProductChoice.value.inputValue = res.management?.name;
      isEdit.value = false;
    } catch (err) {
      console.error(err);
    }
  };

  let refForm = ref();
  let subEdit = async () => {
    try {
      let check = await refForm.value.validate();
      let check2 = productBomDetailList.value.some(({ dosage }, index) => {
        if (!dosage) {
          Message.error('第' + (index + 1) + '条子BOM标准用量未填写');
        }
        return !dosage;
      });
      if (!check && !check2) {
        let data = {
          ...bomDetails,
          productBomDetail: productBomDetailList.value,
        };
        if (bomDetails.id) {
          await EditProductBom({ ...data });
        } else {
          await AddProductBom({
            ...data,
            historyState: route.query.historyId ? 2 : 1,
          });
        }
      }
      isEdit.value = false;
    } catch (err) {
      console.log(err);
    }
  };
  let initialize = async () => {
    try {
      let list: any = await getTableList();
      let item: any = list.find(({ historyState }: any) => historyState === 1);
      await loadBomDetails(item.id || tableList.value[0].id);
    } catch (err) {
      console.error(err);
      //
    }
  };
  initialize();

  let productBomChoice = async (data: any) => {
    if (data.materialProperty === 4) {
      return productBomDetailList.value.push({
        productId: data.id,
        productBomDetail: {
          management: data,
        },
      });
    }
    try {
      let { content } = await GetProductBomPage({
        page: 1,
        size: -1,
        historyState: 1,
        productId: data.id,
      });
      if (!content.length) {
        return Message.error('选择的产品不是委外且没有BOM，请先定义该产品BOM');
      }
      let getBom = await GetProductBom({ id: content[0].id });

      if (!bomDetails.id) {
        productBomDetailList.value.push({
          bomId: getBom.id,
          productBomDetail: getBom,
        });
      }
      let tree = await GetProductBomTree(getBom.id);
      let check = false;
      let ergodicCheck = (list?: any[]) => {
        if (
          list?.some((item) => {
            ergodicCheck(item.children);
            return bomDetails.id === item.id;
          })
        ) {
          check = true;
        }
      };
      ergodicCheck([tree]);
      if (check) {
        return Message.error('选择BOM的子项已包含本BOM，请重新选择');
      }
      productBomDetailList.value.push({
        bomId: getBom.id,
        productBomDetail: getBom,
      });
    } catch (err) {
      //
    }
  };
</script>

<style scoped lang="less">
  .table-info {
    padding: 20px;

    .search-box {
      margin-bottom: 16px;
      display: flex;
      justify-content: space-between;
    }
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }
</style>
